//
//  SINewFeatureView.swift
//  SinaImiate
//
//  Created by xiaoming on 16/7/4.
//  Copyright © 2016年 GoodJob. All rights reserved.
//

import UIKit

class SINewFeatureView: UIView {
    
    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var EnterHome: UIButton!
    
    @IBOutlet weak var pageControl: UIPageControl!
    
    class func newFeatureView() -> SINewFeatureView {
        
        let nib = UINib(nibName: "SINewFeatureView", bundle: nil)
        
        let v = nib.instantiate(withOwner: self, options: nil)[0] as! SINewFeatureView
        
        v.frame = UIScreen.main().bounds
        
        return v
        
    }
    
    override func awakeFromNib() {
        let count = 4
        
        let rect = UIScreen.main().bounds
        
        for i in 0..<count {
                        let imageName = "new_feature_\(i + 1)"
            
            let iv = UIImageView(image: UIImage(named: imageName))
            
            iv.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            
            scrollView.addSubview(iv)
            
        }
        
        scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
        
        scrollView.bounces = false
        scrollView.isPagingEnabled = true
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        
        scrollView.delegate = self
        
        pageControl.isUserInteractionEnabled = false
        
        EnterHome.isHidden = true
        
    }

    
    @IBAction func EnterHome(_ sender: AnyObject) {
        
    }
    
}

extension SINewFeatureView: UIScrollViewDelegate {
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        if page == scrollView.subviews.count {
            ///即将进入主视图,删除新特性
            removeFromSuperview()
        }
        
        EnterHome.isHidden = (page != scrollView.subviews.count - 1)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        EnterHome.isHidden = true
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        
        pageControl.currentPage = page
        
        pageControl.isHidden = (page == scrollView.subviews.count)
        
    }
}
